import { departmentPageApi, departmentSaveApi, departmentUpdateApi, departmentRemoveApi } from '@/api/dept/dept'
import { DeptTable, DeptAdd } from '@/api/dept/deptModel'
import { reactive, onMounted, ref, nextTick } from 'vue'
import { EditType } from '@/type/BaseEnum'
import useInstance from '@/hooks/useInstance';
export default function DeptPageTable() {
  const RefDeptAddEdit = ref<{ show: (type: string, row?: any) => void }>()
  const { global, proxy } = useInstance()
  var searchParams = reactive({
    name: '',
    size: 10,
    page: 1,
    sort: ''
  })
  const deptTableDate = reactive<DeptTable>({
    list: [],
    Loading: false,
    height: 0,
    total: 0
  })
  const deptPageSize = async () => {
    deptTableDate.Loading = true
    const res = await departmentPageApi(searchParams)
    if (res.code === 200) {
      deptTableDate.list = res.data.records
      deptTableDate.Loading = false
      deptTableDate.total = res.data.total
    }
  }
  onMounted(() => {
    deptPageSize()
    nextTick(() => {
      deptTableDate.height = window.innerHeight - 185
    })
  })
  const handleCurrentChange = (current) => {
    searchParams.page = current
    deptPageSize()
  }
  const handleSizeChange = (size) => {
    searchParams.size = size
    deptPageSize()
  }
  const addBtn = () => {
    RefDeptAddEdit?.value?.show(EditType.ADD)
  }
  const editBtn = (row) => {
    RefDeptAddEdit?.value?.show(EditType.EDIT, row)
  }
  const save = async (row: DeptAdd) => {
    console.log(row);

    let res
    if (row?.id) {
      res = await departmentUpdateApi(row)
    } else {
      res = await departmentSaveApi(row)
    }
    if (res.code === 200 && row?.id) {
      global.$message({ message: '编辑成功', type: 'success' })
      searchParams.page = 1
      deptPageSize()
    } else {
      global.$message({ message: '新增成功', type: 'success' })
      searchParams.page = 1
      deptPageSize()
    }
  }
  const deleteBtns = async (id: number | string) => {
    const confirm = await global.$myconfirm('确定删除该部门嘛?')
    if (confirm) {
      const res = await departmentRemoveApi({ id })
      if (res.code === 200) {
        global.$message({ message: '删除成功', type: 'success' })
        if (deptTableDate.list.length === 1 && searchParams.page > 1) {
          searchParams.page -= 1
          deptPageSize()
        } else {
          deptPageSize()
        }
      }
    } else {
      global.$message({ message: "已取消删除", type: 'warning' })
    }
  }
  const tableRowClassName = ({ row, rowIndex }) => {
    if (rowIndex % 2 === 1) {
      return "warning-row";
    } else {
      return "success-row";
    }
  }
  const resetBtn = () => {
    searchParams.name =''
    searchParams.page=1
    searchParams.size = 10
    searchParams.sort=''
    deptPageSize()
  }
  // 删除需要判断 页码
  return {
    deptPageSize, resetBtn, deptTableDate, searchParams, handleCurrentChange, handleSizeChange, RefDeptAddEdit, addBtn, save, editBtn, deleteBtns,tableRowClassName
  }
}